var pddData = {
  goods: [],
  // 价格类型 1 运费公式 2 价格*5
  priceType: "1",
  // 第一个SKU
  firstSku: "30*40",
  // 初始价
  originalPrice: "1872",
  // 商品标题
  goodsTitle: "~~~~",
  // 商品描述
  goodsDesc: "~~~~",
  // 第一个分类描述
  firstClassify: "",
  // 初始化的分类描述 根据是否为空可判断是否只有一个SKU
  filterSkuKind: "",
  pddKeyWordDes: "",
  goodsDetails: [],
};

// 编辑商品详情
function editGoodsDesc() {
  let temp = "";
  let longestSkuLength = 0;
  if (needEmoji) {
    // 设置商品描述前缀
    temp = dlData.prefix + "\n\n🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹\n😀【商品详情】😀\n";

    // 获取最长的SKU
    if (strlen(pddData.goods[pddData.goods.length - 1].sku) > longestSkuLength) {
      longestSkuLength = strlen(pddData.goods[pddData.goods.length - 1].sku);
    }

    // 添加商品详情属性
    pddData.goodsDetails.forEach((e) => {
      temp += e + "\n";
    });
    temp += "🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹";
  } else {
    // 设置商品描述前缀
    temp = dlData.prefix + "\n\n====================\n《【商品详情】》\n";

    // 获取最长的SKU
    if (strlen(pddData.goods[pddData.goods.length - 1].sku) > longestSkuLength) {
      longestSkuLength = strlen(pddData.goods[pddData.goods.length - 1].sku);
    }

    // 添加商品详情属性
    pddData.goodsDetails.forEach((e) => {
      temp += e + "\n";
    });
    temp += "====================";
  }

  temp +=
    "\n\n【其他現貨尺寸下標指南】:如價格為290，下標先選擇對應花色，再選擇客製尺寸，數量欄輸入29即可！下单请备注尺寸\n\n【商品尺寸、价格】\n";

  // 添加SKU
  pddData.goods.forEach((element, index1) => {
    element.targetPrice = Math.floor(
      (element.originPrice * pddData.originalPrice) / 2
    );

    let addSpaceNum = longestSkuLength - strlen(element.sku);
    let str = "";
    for (var i = 0; i < addSpaceNum; i++) {
      str = str + "\xa0";
    }
    temp += `${element.sku}\xa0\xa0\xa0\xa0${str}\xa0\xa0\xa0\xa0${element.targetPrice}元\n`;
  });

  // 添加后缀
  temp += dlData.suffix + "\n\n";

  // 添加关键词
  temp += pddData.pddKeyWordDes + "\n\n";

  return temp;
}

// 修改商品title
function addGoodsSuffix() {
  return new Promise(async (resolve, reject) => {
    // 找到句柄
    let handle = $('#appRoot div[title="商品名称"]').next();
    let inputHandle = handle.find("input")[0];
    handle = handle.find(".shopee-sensitive-words-input__mask");

    handle.click(async (e) => {
      await wait(500);

      // 清除事件
      // 点击后出来input才能执行，需要放在timeout中
      await inputValue(inputHandle, pddData.goodsTitle);
      handle.unbind(e);
      resolve();
    });

    // 手动触发
    handle.click();
  });
}

// 添加商品描述
function addGoodsDesc() {
  return new Promise(async (resolve, reject) => {
    // 找到句柄
    let handle = $('#appRoot  div[title="描述"]').next();
    let inputHandle = handle.find("textarea")[0];
    handle = handle.find(".shopee-sensitive-words-input__mask");

    handle.click(async (e) => {
      await wait(500);

      // 判断价格模板类型
      switch (pddData.priceType) {
        // 价格类型为运费模板
        case "1": {
          break;
        }
        // 价格5倍
        case "2": {
          pddData.goodsDesc = editGoodsDesc();
          break;
        }
        default: {
          console.log("设置折扣值:数据有问题~");
          break;
        }
      }

      // 点击后出来input才能执行，需要放在timeout中
      await inputValue(inputHandle, pddData.goodsDesc);
      // 清除事件
      handle.unbind(e);
      resolve();
    });

    // 手动触发
    handle[0].click();
  });
}

// 物流信息
async function expressInfo() {
  anchors("物流信息");
  // 商品重量
  var spzlInput = $("#post-product-logistic div[title=商品重量]")
    .next()
    .find("input")[0];
  inputValue(spzlInput, spzl);

  // 商品尺寸
  var spccInput = $("#post-product-logistic div[title=商品尺寸]").next().find("input");
  inputValue(spccInput[0], spcc[0]);
  inputValue(spccInput[1], spcc[1]);
  inputValue(spccInput[2], spcc[2]);

  // 发货时间
  var spsjInput = $("#post-product-logistic div[title=发货时间]")
    .next()
    .find("input")[0];
  inputValue(spsjInput, $("#expressInput").val());

  // 商品保存状况
  await selectItem("全新");
}

// 批量编辑
async function bulkEdit(timeout = 1000) {
  anchors("批量编辑");
  return new Promise(async (resolve, reject) => {

    // 小数处理方式
    switch (pddData.priceType) {
      // 价格类型为运费模板
      case "1": {
        selectItem("取整");
        break;
      }
      // 价格5倍
      case "2": {
        selectItem("保留两位小数");
        break;
      }
      default: {
        console.log("设置折扣值:数据有问题~");
        break;
      }
    }

    // 规格编码
    await inputValue($('input[aria-label="规格编码"]')[0], timestamp);

    // 价格
    var originalPriceInput = $('div[title="批量编辑"]')
      .parent()
      .find('input[aria-label="价格"]')[0];
    await inputValue(originalPriceInput, pddData.originalPrice);

    // 库存
    var stockInput = $('div[title="批量编辑"]')
      .parent()
      .find('input[aria-label="库存"]')[0];
    await inputValue(stockInput, stock);

    await wait(1000);


    console.log(111111);

    // 判断价格模板类型
    switch (pddData.priceType) {
      case "2": {
        // 价格计算方式
        await selectItem("相乘");

        await wait(1000);
        // 先设置通用价格
        await initGeneralPrice();

        break;
      }
      default: {
        console.log("批量编辑:bulkEdit,数据有问题~");
        break;
      }
    }

    await wait(1000);
    // 批量编辑一键设置按钮
    var btn = getHandleBySelectorAndText(
      $(".v-btn__content"),
      "一键设置",
      true
    );
    btn[0].click();
    await wait(timeout);

    resolve();
  });
}

// 设置通用价格
async function initGeneralPrice() {
  let temps = getHandleBySelectorAndText($(".v-table td"), generalSku, true);
  // 判断价格模板类型
  switch (pddData.priceType) {
    // 价格类型为运费模板
    case "1": {
      break;
    }
    // 价格5倍
    case "2": {
      // 遍历出最高价
      let trList = $('div[title="商品规格列表"]').next().find("tbody tr");
      let maximalPrice = 0;
      let trPrice = 0;
      let temp = "";

      for (var j = 0; j < trList.length; j++) {
        // 获取每一列第一个input的值，就是价格
        trPrice = trList
          .eq(j)
          .find(".k-text-field-content-value__text")
          .eq(0)
          .text();
        trPrice = trPrice == "" ? 0 : parseFloat(trPrice);
        // 获取最大值
        maximalPrice = maximalPrice > trPrice ? maximalPrice : trPrice;
      }

      for (var i = 0; i < temps.length; i++) {
        temp =
          temps[i].next().find(".k-text-field__input").length > 0
            ? temps[i].next().find(".k-text-field__input")[0]
            : temps[i].next().next().find(".k-text-field__input")[0];
        await inputValue(temp, (parseFloat(maximalPrice) / 4.5).toFixed(2));
      }
      break;
    }
    default: {
      break;
    }
  }
}

// 初始化SKU
async function initSku(timeout = 1000) {
  // 删除默认SKU
  async function deleteSku(deleteBtn, timeout = 100) {
    return new Promise(async (resolve, reject) => {
      await wait(timeout);
      deleteBtn.trigger("click");
      resolve();
    });
  }

  // 添加新的SKU
  function addSku(skuIndex, skuName) {
    return new Promise((resolve, reject) => {
      setTimeout(async () => {
        let skuHandle = $(".variation-option-creator:eq(" + skuIndex + ")")
          .find("input")
          .last()[0];
        await inputValue(skuHandle, skuName);
        resolve();
      }, 1000);
    });
  }

  return new Promise(async (resolve, reject) => {
    var handle = $(".variation-option-creator");
    let arr = Array.from(handle);
    /** 多余的价格相关SKU */
    let moreSkuSize = 0;
    switch (pddData.priceType) {
      case "1": {
        // 如果只有一个SKU
        if (pddData.filterSkuKind == "") {
          // 添加通用SKU
          $(".variation-option-creator:eq(0)").find("button").eq(0).click();
          await addSku(0, generalSku);
          resolve();
          return;
        }

        // 第一个SKU不能超过50个
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value !=
            pddData.filterSkuKind
          ) {
            let more =
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              ).length - 25;
            for (var i = 0; i < more; i++) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .last()
              );
            }
          }
        }
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value ==
            pddData.filterSkuKind
          ) {
            subSkuIndex = ai;
            while (
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              )[0]
            ) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .eq(0)
              );
            }

            // 添加第一个有用SKU
            $(".variation-option-creator:eq(" + ai + ")")
              .find("button")
              .eq(0)
              .click();
            await addSku(ai, pddData.firstSku);

            // 添加通用SKU
            $(".variation-option-creator:eq(" + ai + ")")
              .find("button")
              .eq(0)
              .click();
            await addSku(ai, generalSku);
          }
        }
        await wait(timeout);
        resolve();
        break;
      }
      case "2": {
        let minorSkuSize = 1;
        /** 1个SKU */
        if (pddData.filterSkuKind == "") {
          minorSkuSize = $(".variation-option-creator:eq(0)").find(
            ".v-input__append-outer i"
          ).length;
          let more1 = minorSkuSize - 49;

          // 价格5倍内
          // 获取最低价
          let miniPrice = pddData.goods[0].targetPrice;
          let maxPriceIndex = 0;
          // 遍历第几个后是5倍内，并获取其索引
          for (var gi = 0; gi < pddData.goods.length; gi++) {
            maxPriceIndex =
              pddData.goods[gi].targetPrice < 5 * miniPrice
                ? gi
                : maxPriceIndex;
          }

          // 重新拆分goods
          pddData.goods = pddData.goods.slice(0, maxPriceIndex + 1);

          let goodsLength = pddData.goods.length;
          let kyyGoods = $(".variation-option-creator:eq(0)").find(
            '.v-text-field__slot input[aria-label="选项"]'
          );
          let kyySkuLength = kyyGoods.length;
          let isExist = false;
          let delArr = [];

          // 排除无效的SKU
          for (var k = 0; k < kyySkuLength; k++) {
            isExist = false;
            for (var j = 0; j < goodsLength; j++) {
              if (kyyGoods.eq(k).val() == pddData.goods[j].sku) {
                isExist = true;
                break;
              }
            }
            if (!isExist) {
              delArr.unshift(k);
            }
          }

          // 删除掉无效的sku，从后往前删
          for (var di = 0; di < delArr.length; di++) {
            await deleteSku(
              $(".variation-option-creator:eq(0)")
                .find(".v-input__append-outer i")
                .eq(delArr[di])
            );
          }

          // 删除多余的SKU，只留下49个
          for (var i = 0; i < more1; i++) {
            await deleteSku(
              $(".variation-option-creator:eq(0)")
                .find(".v-input__append-outer i")
                .last()
            );
          }

          // 添加通用SKU
          $(".variation-option-creator:eq(0)").find("button").eq(0).click();
          await addSku(0, generalSku);
          await wait(timeout);
          resolve();
          return;
        }

        /** 2个SKU */
        // 获取次要SKU的数量，不包括（通用）
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value ==
            pddData.filterSkuKind
          ) {
            minorSkuSize = $(".variation-option-creator:eq(" + ai + ")").find(
              ".v-input__append-outer i"
            ).length;
          }
        }

        // 第一个SKU不能超过25个
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value !=
            pddData.filterSkuKind
          ) {
            let more =
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              ).length - 25;
            for (var i = 0; i < more; i++) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .last()
              );
            }
            moreSkuSize = Math.floor(
              50 /
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              ).length
            );
          }
        }

        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value ==
            pddData.filterSkuKind
          ) {
            subSkuIndex = ai;

            goods = pddData.goods;

            // 获取最低价
            let miniPrice = goods[0].targetPrice;
            let maxPriceIndex = 0;
            // 遍历第几个后是5倍内，并获取其索引
            for (var gi = 0; gi < goods.length; gi++) {
              maxPriceIndex =
                goods[gi].targetPrice < 5 * miniPrice ? gi : maxPriceIndex;
            }

            // 重新拆分goods
            goods = goods.slice(0, maxPriceIndex + 1);

            let goodsLength = goods.length;
            let kyyGoods = $(".variation-option-creator:eq(" + ai + ")").find(
              '.v-text-field__slot input[aria-label="选项"]'
            );
            let kyySkuLength = kyyGoods.length;
            let isExist = false;
            let delArr = [];

            // 排除无效的SKU
            for (var k = 0; k < kyySkuLength; k++) {
              isExist = false;
              for (var j = 0; j < goodsLength; j++) {
                if (kyyGoods.eq(k).val() == goods[j].sku) {
                  isExist = true;
                  break;
                }
              }
              if (!isExist) {
                delArr.unshift(k);
              }
            }

            // 删除掉无效的sku，从后往前删
            for (var di = 0; di < delArr.length; di++) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .eq(delArr[di])
              );
            }

            // 排序多余的SKU
            if (goodsLength > moreSkuSize - 1) {
              let moreLength = goodsLength - (moreSkuSize - 1);
              while (moreLength--) {
                await deleteSku(
                  $(".variation-option-creator:eq(" + ai + ")")
                    .find(".v-input__append-outer i")
                    .last()
                );
              }
            }

            // 添加通用SKU
            $(".variation-option-creator:eq(" + ai + ")")
              .find("button")
              .eq(0)
              .click();
            await addSku(ai, generalSku);
          }
        }
        await wait(timeout);
        resolve();
        break;
      }
      default: {
        console.log("initSku error");
        break;
      }
    }
  });
}

// 设置类目
async function initShopCategory() {
  anchors("店铺和类目");
  // 点击展开
  let handle = $("a.k-super-expander-footer__active:contains('展开')");
  console.log("handle......:", handle);
  handle[0].click();

  await selectItem("NoBrand");
  await selectItem("Mainland China (中国大陆)");
}

function selectTW(timeout = 2000) {
  // 台湾站点按钮
  return new Promise((resolve, reject) => {
    var twBtn = document.querySelectorAll(
      "#main .v-content__wrap .v-tabs__item"
    )[1];
    twBtn.click();
    setTimeout(async () => {
      // 选择店铺
      await selectItem("Lily-house 🎀北歐家居館");

      resolve();
    }, timeout);
  });
}